#include <iostream>
#include <cstring>
#include <unistd.h>
#include <functional>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc, char *argv[]) 
{    
    if(argc != 3)
    {
        perror("parameter");
        exit(-1);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    
    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    ::inet_pton(AF_INET, serverip.c_str(), &server.sin_addr);

    if(connect(sockfd, (struct sockaddr*)&server, sizeof(server)) < 0) 
    {
        perror("connect");
        exit(1);
    }    

    while(1)
    {
        std::cout << "[client say]# ";
        std::string message;
        std::getline(std::cin, message);

        if(message.empty()) continue;

        write(sockfd, message.c_str(), message.size());
        
        char buffer[1024];
        ssize_t n = read(sockfd, buffer, sizeof(buffer) - 1);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
        else
            break;
        
    }


    return 0;
}